package com.shebei.api.equipment_api_test.http.performance;

import com.alibaba.fastjson.JSON;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class HttpClientPostObject {


    public    String doPostJson(String url,  Object myclass, Map<String, String> head) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求

            HttpPost httpPost = new HttpPost(url);

            if (head != null){
                for (String key : head.keySet()) {
                    httpPost.setHeader(key,String.valueOf(head.get(key)));
                }


            }
            String jsonSting = JSON.toJSONString(myclass);


                StringEntity entity = new StringEntity(jsonSting, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);


            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println("请求response为："+resultString);
        } catch (Exception e) {
            // log.error(e.getMessage(),e);
        } finally {
            try {
                if (null !=response){
                    response.close();
                }
            } catch (IOException e) {
                // log.error(e.getMessage(),e);
            }
        }

        return resultString;
    }
}
